<template>
	<div>
	<list class="list" loadmoreoffset="5" @loadmore="loadmore()">
		<header>
			<view class="list-item-head">
				<!-- <text class="list-item-text-image">图片</text> -->
				<text class="list-item-text-id">id</text>

				<text class="list-item-text-epc">epc</text>
				<text class="list-item-text-count">总数</text>
				<text class="list-item-text-rssi">rssi</text>
			</view>
		</header>
<!-- 		<cell v-for="(item, index) in goodInfo" v-bind:key="item.name" >
			<view class="list-item">
				<image :src="item.fig" class="list-item-image"></image>
				<text class="list-item-text-id">{{item.name}}</text>
				<text class="list-item-text-count">{{item.count}}</text>
			</view>
		</cell> -->
		<cell v-for="(item, index) in page_state.dataList" v-bind:key="item.id" >
			<view class="list-item">
				<text class="list-item-text-id">{{item.id}}</text>
				<text class="list-item-text-epc">{{item.epc}}</text>
				<text class="list-item-text-count">{{item.count}}</text>
				<text class="list-item-text-rssi">{{item.rssi}}</text>
			</view>
		</cell>
	</list>
	<view class="btn-box">
		<button type="primary"  @click="inventory()" style="flex: 3;">{{page_state.btn1Info}}</button>
		<button type="primary" :disabled="page_state.btn2Disabled" @click="inventoryTimer()()"
			style="flex: 3;margin-left: 5px;">定时盘点</button>
		<button type="primary" :disabled="page_state.btn3Disabled" @click="clear()"
			style="flex: 1;margin-left: 5px;">清空</button>
	</view>

	</div>
</template>

<script>
	import { cacheUtils }from '@/util/cache.js'
export default {
  data() {
    return {
      page_state: {
        btn1Info: "开始盘点",
        tagsAmount: 0,
        btn2Disabled: false,
        btn3Disabled: false,
        cbDisabled: false,
        dataList: []
      },
	  goodInfo: [],
      main: null,
      hhwUHFController: null,
      globalEvent: null,
      pageNum: 100,
      offset: 50,
      epcList: [],
      tempList: [],
      async_flag: false,
      voice_flag: true,
      keyDownTime: 1,
      barcode_flag: false,
	  receiver: null,
	  loadShowFlag: 0,
    };
  },
  created() {
    this.init();
  },
  mounted() {
    this.Show();
  },
  beforeDestroy() {
    this.Hide();
  },
  methods: {
    init() {
      // 这里将Vue 3的 onLoad() 逻辑放入 Vue 2的 created() 钩子中
      // 注册事件监听等初始化操作
      this.hhwUHFController = getApp().globalData.hhwUHFController;
      this.globalEvent = getApp().globalData.globalEvent;

// console.log("init...")
      this.globalEvent.addEventListener('uhf_tag_event', (e)=> {
      	console.log(e.tag_info_list)
      	var result = e.tag_info_list
      	if (result == null) {
      		// 接收到停止盘点的回调消息
      		var event = e.inventory_event
      		if (event == "stopInventory") {
      			uni.showToast({
      				title: "停止盘点",
      				icon: "none"
      			})
      			this.page_state.btn2Disabled = false
      			this.page_state.btn3Disabled = false
      			this.page_state.cbDisabled = false
      			this.page_state.btn1Info = "开始盘点"

      		}
      		return
      	}
      	// 接收盘点到的标签信息
      	for (var i = 0; i < result.length; i++) {
      	  var id = i;
      	  var epc = this.bytes2HexString(result[i].EpcId);
      	  var rssi = result[i].RSSI;
      	  // 获取标签tid，配合startEpcTidInventory使用
      	  // var EmbededData = bytes2HexString(result[i].EmbededData)
      	  // console.log("tagEpcTidInventoryByTimer", "epc:" + epc ,  "Tid: " + EmbededData)
      	  var tag = {
      	    id: id,
      	    epc: epc,
      	    count: 1,
      	    rssi: rssi,
      	  };
      	
      	  // 过滤掉 epc 不以 "AA" 开头的项
      	  if (!/^12/.test(epc)) {
      	    continue; // 如果 epc 不以 "AA" 开头，则跳过此项
      	  }
      	
      	  var index = this.epcList.indexOf(epc);
      	  if (index == -1) {
      	    tag.id = this.epcList.length;
      	    if (this.page_state.dataList.length < this.offset) {
      	      this.page_state.dataList.push(tag);
      	    }
      	    this.tempList.push(tag);
      	    this.epcList.push(epc);
      	  } else {
			  // continue
      	    tag.id = index;
      	    tag.count = this.tempList[index].count + 1;
      	    if (index < this.page_state.dataList.length) {
      	      this.page_state.dataList.splice(index, 1, tag);
      	    }
      	    this.tempList.splice(index, 1, tag);
      	  }
      	}

      	this.page_state.tagsAmount = this.epcList.length
      })
    },
    Show() {
		this.main = plus.android.runtimeMainActivity();
		console.log("inventory Show")
		// 初始化二维码扫描，以防扫描服务处于关闭状态，而无法调用扫描
		this.initBarcodeScan()
		// 屏蔽二维码扫描扳机，以便app可以自定义触发
		this.disableBarcodeScanKey()
		// 监听功能按键，触发扫描
		var IntentFilter = plus.android.importClass('android.content.IntentFilter')
		var filter = new IntentFilter()
		filter.addAction("android.rfid.FUN_KEY")
		this.receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
			onReceive: (context, intent) =>{
				plus.android.importClass(intent)
				var code = intent.getIntExtra("keyCode", 0)
				var keyDown = intent.getBooleanExtra("keydown", false)

				if (keyDown  && code == 134) {
					console.log("inventory", "receive keyUp code: " + code)
					if (this.barcode_flag) {
						// 开始扫描
						this.startBarcodeScan()
					} else {
						// 开始超高频
						this.startInventory()
					}
					keyDownTime++
				} else if (!keyDown) {
					if (this.barcode_flag) {
						// 停止扫描
						this.stopBarcodeScan()
					} else {
						// 停止超高频
						this.stopInventory()
					}
					keyDownTime = 1
				}
			}
		})
		this.main.registerReceiver(this.receiver, filter)
    },
    Hide() {
		console.log("inventory Hide")
      // Vue 3的 onHide() 逻辑
      this.main.unregisterReceiver(this.receiver);
    },
    // 其他方法，如disableBarcodeScanKey, bytes2HexString, hexString2Bytes等
	disableBarcodeScanKey(){
		var Intent = plus.android.importClass("android.content.Intent")
		var intent = new Intent("com.rfid.KEY_SET")
		var keyValueArray = ["134"]
		intent.putExtra("keyValueArray", keyValueArray)
		intent.putExtra("134", false)
		this.main.sendBroadcast(intent)
	},
	bytes2HexString(byteArray) {
		return Array.from(byteArray, function(byte) {
			return ('0' + (byte & 0xFF).toString(16)).slice(-2)
		}).join('')
	},
	hexString2Bytes(str) {
		var pos = 0
		var len = str.length
		if (len % 2 != 0) {
			return null
		}
		len /= 2
		var hexA = new Array()
		for (var i = 0; i < len; i++) {
			var s = str.substr(pos, 2)
			var v = parseInt(s, 16)
			hexA.push(v)
			pos += 2
		}
		return hexA
	},
	initBarcodeScan() {
		var Intent = plus.android.importClass("android.content.Intent")
		var intent = new Intent("com.rfid.SCAN_INIT")
		this.main.sendBroadcast(intent);
	},
	startBarcodeScan() {
		var Intent = plus.android.importClass("android.content.Intent")
		var intent = new Intent("com.rfid.SCAN_CMD")
		this.main.sendBroadcast(intent);
	},
	
	stopBarcodeScan() {
		var Intent = plus.android.importClass("android.content.Intent")
		var intent = new Intent("com.rfid.STOP_SCAN")
		this.main.sendBroadcast(intent);
	},
	
	inventory() {
		if (this.page_state.btn1Info == "开始盘点") {
			this.startInventory()
		} else {
			this.stopInventory()
		}
	},
	startInventory() {
		this.page_state.btn2Disabled = true
		this.page_state.btn3Disabled = true
		this.page_state.cbDisabled = true
		this.page_state.btn1Info = "停止盘点"
		// 盘点过滤数据
		var fdata = this.hexString2Bytes("")
		// 盘点过滤数据区域，1 => EPC区，2 => TID区，3 => USER区
		var fbank = 1
		// 盘点过滤起始地址，指标签数据区域的起始地址，比如：3，代表从标签数据区的第3*2个字节开始匹配数据；EPC区需要从2开始，详情参考“标签读写注意事项”中关于EPC区数据结构的描述
		var fstartaddr = 2
		// 显示匹配的标签，或不匹配的标签。true => 显示匹配的标签，false => 显示不匹配的标签
		var matching = true
		// 设置盘点过滤条件
		
		
		this.hhwUHFController.setInventoryFilter(fdata, fbank, fstartaddr, matching, result => {
			console.log("inventory inventory", "setInventoryFilter " + result)
		})
		if (this.async_flag) {
			// 设置盘点的session为1
			// 	console.log("inventory inventory", "async setGen2session: " + result)
				// 大量标签场景（200张标签以上），开始异步盘点，手动调用停止盘点后，停止盘点
				this.hhwUHFController.startInventory(30, 1, true, 0, this.voice_flag, result => {
					console.log("inventory inventory", "startInventory " + result)
				})
			// })
		} else {
			// 设置盘点的session为0
				console.log("async_flag")
				// 少量标签场景（200张标签以下），开始同步盘点，手动调用停止盘点后，停止盘点
				this.hhwUHFController.startInventory(30, false, 0, this.voice_flag, result => {
					console.log("inventory inventory", "startInventory " + result)
				})	
		}
		// })
		},
		stopInventory() {
			// 停止盘点，注意stopInventory中的参数值需要和startInventory第一个参数值对应
			if (this.async_flag) {
				this.hhwUHFController.stopInventory(true)
			} else {
				this.hhwUHFController.stopInventory(false)
			}
			
			this.afterScan()
		},
		clear() {
			this.page_state.dataList = []
			this.goodInfo=[]
			this.loadShowFlag=0
			this.tempList = []
			this.epcList = []
			this.page_state.tagsAmount = 0
			this.offset = 50
		},
		inventoryTimer() {
			uni.showToast({
				title: "开启10S定时盘点",
				icon: "none"
			})
			this.page_state.btn2Disabled = true
			this.page_state.btn3Disabled = true
			this.page_state.cbDisabled = true
			this.page_state.btn1Info = "停止盘点"
			// 取消盘点过滤
			//hhwUHFController.setCancleInventoryFilter(result => {
			//	console.log("inventory inventoryTimer", "setCancleInventoryFilter: " + result)
			//})
				if (this.async_flag) {
					// 设置盘点的session为1
					// hhwUHFController.setGen2session(1, result => {
						// console.log("inventory inventoryTimer", "async setGen2session: " + result)
						// 大量标签场景（200张标签以上），开始异步盘点，10000ms后，自动停止盘点
						// hhwUHFController.startInventory(true, 10000, voice_flag)
						this.hhwUHFController.startInventory(30, 1, true, 10000, this.voice_flag, result => {
							console.log("inventory inventory", "startInventory " + result)
						})
					// })
				} else {
					// 设置盘点的session为0
					// hhwUHFController.setGen2session(0, result => {
						// console.log("inventory inventoryTimer", "sync setGen2session: " + result)
						// 少量标签场景（200张标签以下），开始同步盘点，10000ms后，自动停止盘点
						// hhwUHFController.startInventory(false, 10000, voice_flag)
						this.hhwUHFController.startInventory(30, 0, false, 10000, this.voice_flag, result => {
							console.log("inventory inventory", "startInventory " + result)
						})
					// })
				}
			// })
		},
		loadmore() {
			console.log("inventory loadmore", "dataList size1: " + this.page_state.dataList.length, "temList size: " + this.tempList.length)
			if (this.page_state.dataList.length >= this.tempList.length) {
				console.log("inventory loadmore", "nomore")
				return
			}
			// 每次加载pageNum个
			var size
			if (this.tempList.length - this.offset >= this.pageNum) {
				size = this.pageNum
			} else {
				size = this.tempList.length - this.offset
			}
			for (var i = this.offset; i < size + this.offset; i++) {
				this.page_state.dataList.push(this.tempList[i])
			}
			this.offset = this.offset + size
		},
		// async afterScan(){
		// 	      const pattern = /^12/;
			
		// 	      // 过滤 this.page_state.dataList 数组，保留 epc 以 "AA" 开头的项
		// 	      this.page_state.dataList = this.page_state.dataList.filter(item => {
		// 	        return pattern.test(item.epc);
		// 	      });
		// }
	
  }
}
</script>

<style lang="scss" scoped>
	.list {
		flex: 1;
		background-color: #ebebeb;
	}

	.list-item-head {
		display: flex;
		flex-direction: row;
		background-color: #fff;
	}

	.list-item {
		display: flex;
		flex-direction: row;
		background-color: #fff;
	}

	.list-item-text-id {
		width: 65px;
		padding-left: 5px;
		padding-right: 5px;
		padding-top: 8px;
		padding-bottom: 8px;
		font-size: 16px;
	}

	.list-item-text-epc {
		width: 247px;
		padding-left: 5px;
		padding-right: 5px;
		padding-top: 8px;
		padding-bottom: 8px;
		font-size: 16px;
	}

	.list-item-text-count {
		width: 65px;
		padding-left: 5px;
		padding-right: 5px;
		padding-top: 8px;
		padding-bottom: 8px;
		font-size: 16px;
	}
	.list-item-text-image {
		width: 400px;
		padding-left: 5px;
		padding-right: 5px;
		padding-top: 8px;
		padding-bottom: 8px;
		font-size: 16px;
	}

	.list-item-text-rssi {
		width: 35px;
		padding-left: 5px;
		padding-right: 5px;
		padding-top: 8px;
		padding-bottom: 8px;
		font-size: 16px;
	}

	.btn-box {
		display: flex;
		flex-direction: row;
		background-color: #fff;
		padding-bottom: 5px;
		padding-left: 5px;
		padding-right: 5px;
		align-items: center;
	}
</style>
